﻿using Common;
using Common.SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1.Task;
using TouchSocket;
using TouchSocket.Sockets;
using System.Net.Sockets;
using TouchSocket.Core;
using TcpClient = TouchSocket.Sockets.TcpClient;
using Motion.ZmcAct;
using Common.Entity;
using System.Configuration;
using System.Diagnostics;

namespace WindowsFormsApp1
{
    public partial class MainForm : UIForm
    {
        TcpClient TCPVisionClient = new TcpClient();
        bool isConnect = false;
        string dataReceive = string.Empty;
        public MainForm()
        {
            InitializeComponent();
            SqlSugarHelper.Instance.Init();
            Log.Debug("软件打开");
            //MainTask mainTask = new MainTask();
            //Thread thread = new Thread(mainTask.Run);        
            //thread.Start();
            //连接正运动
       

            ZMC.Instance.Connect(ConfigurationManager.AppSettings["zmcIp"]);
            if (ZMC.Instance.IsLink)
            {
                
            }
            else
            {
                Log.Warn("正运动连接失败");
            }
            TCPVisionClient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到服务器，此时已经创建socket，但是还未建立tcp
            TCPVisionClient.Connected = (client, e) =>
            {
                isConnect = true;
                return EasyTask.CompletedTask;
            };//成功连接到服务器
            TCPVisionClient.Disconnecting = (client, e) =>
            {
                isConnect = false;
                return EasyTask.CompletedTask;
            };//即将从服务器断开连接。此处仅主动断开才有效。
            TCPVisionClient.Disconnected = (client, e) =>
            {
                isConnect = false;
                return EasyTask.CompletedTask;
            };//从服务器断开连接，当连接不成功时不会触发。
            TCPVisionClient.Received = (client, e) =>
            {
                //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
                var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
                if (tbxCommunication.InvokeRequired)
                {
                    tbxCommunication.BeginInvoke(new Action(() =>
                    {
                        tbxCommunication.Text +=DateTime.Now.ToString() + "收到数据:" + mes + Environment.NewLine;
                        dataReceive = mes;
                    }));
                }
                else
                {
                    tbxCommunication.Text += DateTime.Now.ToString() + mes + Environment.NewLine;
                }
                Log.Info($"客户端接收到信息：{mes}");
                return EasyTask.CompletedTask;
            };

            //载入配置
            TCPVisionClient.Setup(new TouchSocketConfig()
                .SetRemoteIPHost(ConfigurationManager.AppSettings["VisionIPAndPort"])
                .ConfigureContainer(a =>
                {
                    a.AddConsoleLogger();//添加一个日志注入
                }).ConfigurePlugins(a =>
                {
                    a.UseReconnection()
                     .SetTick(TimeSpan.FromSeconds(1))
                     .UsePolling();

                }));
            try
            {
                TCPVisionClient.Connect();//调用连接，当连接不成功时，会抛出异常。
            }
            catch (AggregateException ex)
            {
                Log.Warn(ex.Message);
            }
        }
        float ga_AlarmCodeLast;

        private void timer1_Tick(object sender, EventArgs e)
        {
            var zmc = ZMC.Instance;
            uiLabel1.Text = isConnect ? "TCP已连接" : "TCP未连接";
            ZMC.Instance.ReadUserVar("ga_MainState", out float ga_MainState);
            ShowDevStatus((int)ga_MainState);

            zmc.ReadUserVar("ga_AlarmCode", out float ga_AlarmCode);
            if (ga_AlarmCodeLast != ga_AlarmCode)
            {
                if (ga_AlarmCode != 0)
                {

                    string ngInfo = SqlSugarHelper.Instance.Db.Queryable<PLCErrorCode>().First( u=>u.Code==ga_AlarmCode)?.Info;
                    if (string.IsNullOrEmpty(ngInfo))
                    {
                        ngInfo = $"未知异常,code{ga_AlarmCode}";
                    }
                    Log.Warn($"{(int)ga_AlarmCode}.{ngInfo}");
                }
                else if (ga_AlarmCodeLast != 0)//说明上次异常 这次不异常  已经plc清空了
                {
                    uiScrollingText1.Text = string.Empty;
                }
                ga_AlarmCodeLast = ga_AlarmCode;

                //uiScrollingText1.Text= ngInfo;
            }

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            tbxCommunication.Clear();
            dataReceive = null;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!isConnect)
                return;
            dataReceive = null;
            TCPVisionClient.Send(tbxSend.Text);
            tbxCommunication.Text += DateTime.Now.ToString() + "发送数据:" + tbxSend.Text + Environment.NewLine;
        }
        void ShowDevStatus(int state)
        {
            ZMC zmc = ZMC.Instance;
            if (!zmc.IsLink)
            {
                lblDevStatus.Text = "控制器未连接";
                return;
            }
                zmc.ReadUserVar("gv_InitStatus", out float gv_InitStatus);
            string str = string.Empty;

            if (state == 0 && gv_InitStatus == 0)
            {
                str = "待机";
            }
            else if (state == 0 && gv_InitStatus == 1)
            {
                str = "准备就绪";
            }
            else if (state == 1)
            {
                str = "自动运行中";
            }
            else if (state == 2)
            {
                str = "暂停";
            }
            else if (state == 3)
            {
                str = "复位";
            }
            else if (state == 4)
            {
                str = "报警";
            }
            else if (state == 5)
            {
                str = "报警清除 ";
            }
            else if (state == 6)
            {
                str = "未初始化 ";
            }
            if (lblDevStatus.Text != str)
            {
                lblDevStatus.Text = str;
            }
        }

        private void uiImageButton1_Click(object sender, EventArgs e)
        {
            Process.Start("https://github.com/lovestudyyingyingying");
        }
    }
}
